<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户名称" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入用户名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="部门名称" prop="deptName">
        <el-input
          v-model="queryParams.deptName"
          placeholder="请输入部门名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="请假类型" prop="leaveType">
        <el-select v-model="queryParams.leaveType" placeholder="请假类型" clearable>
          <el-option label="事假" value="personal" />
          <el-option label="病假" value="sick" />
          <el-option label="年假" value="annual" />
          <el-option label="调休" value="compensatory" />
          <el-option label="其他" value="other" />
        </el-select>
      </el-form-item>
      <el-form-item label="请假时间">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="审批状态" clearable>
          <el-option label="待审批" value="0" />
          <el-option label="已通过" value="1" />
          <el-option label="已驳回" value="2" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-date"
          size="mini"
          @click="handleLeave"
          v-hasPermi="['system:attendance:clock']"
        >请假申请</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:attendance:remove']"
        >批量删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:attendance:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="leaveList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="申请ID" align="center" prop="leaveId" />
      <el-table-column label="用户名称" align="center" prop="userName" />
      <el-table-column label="部门名称" align="center" prop="deptName" />
      <el-table-column label="请假类型" align="center" prop="leaveType">
        <template slot-scope="scope">
          <span v-if="scope.row.leaveType === 'personal'">事假</span>
          <span v-else-if="scope.row.leaveType === 'sick'">病假</span>
          <span v-else-if="scope.row.leaveType === 'annual'">年假</span>
          <span v-else-if="scope.row.leaveType === 'compensatory'">调休</span>
          <span v-else-if="scope.row.leaveType === 'other'">其他</span>
          <span v-else>{{ scope.row.leaveType }}</span>
        </template>
      </el-table-column>
      <el-table-column label="开始时间" align="center" prop="startTime" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" prop="endTime" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="请假原因" align="center" prop="reason" :show-overflow-tooltip="true" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-tag :type="getStatusType(scope.row.status)" size="mini">
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="申请时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
          >详情</el-button>
          <el-button
            v-if="scope.row.status === '0'"
            size="mini"
            type="text"
            icon="el-icon-check"
            @click="handleApprove(scope.row, '1')"
            v-hasPermi="['system:attendance:edit']"
          >通过</el-button>
          <el-button
            v-if="scope.row.status === '0'"
            size="mini"
            type="text"
            icon="el-icon-close"
            @click="handleApprove(scope.row, '2')"
            v-hasPermi="['system:attendance:edit']"
          >驳回</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:attendance:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 请假申请对话框 -->
    <el-dialog title="请假申请" :visible.sync="leaveOpen" width="500px" append-to-body>
      <el-form ref="leaveForm" :model="leaveForm" :rules="leaveRules" label-width="100px">
        <el-form-item label="请假类型" prop="leaveType">
          <el-select v-model="leaveForm.leaveType" placeholder="请选择请假类型">
            <el-option label="事假" value="personal"></el-option>
            <el-option label="病假" value="sick"></el-option>
            <el-option label="年假" value="annual"></el-option>
            <el-option label="调休" value="compensatory"></el-option>
            <el-option label="其他" value="other"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker
            v-model="leaveForm.startTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker
            v-model="leaveForm.endTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择结束时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="请假原因" prop="reason">
          <el-input v-model="leaveForm.reason" type="textarea" placeholder="请输入请假原因" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitLeave">提 交</el-button>
        <el-button @click="cancelLeave">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 审批对话框 -->
    <el-dialog title="审批请假申请" :visible.sync="approveOpen" width="500px" append-to-body>
      <el-form ref="approveForm" :model="approveForm" :rules="approveRules" label-width="100px">
        <el-form-item label="审批结果" prop="status">
          <el-radio-group v-model="approveForm.status">
            <el-radio label="1">通过</el-radio>
            <el-radio label="2">驳回</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审批备注" prop="remark">
          <el-input v-model="approveForm.remark" type="textarea" placeholder="请输入审批备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitApprove">确 定</el-button>
        <el-button @click="cancelApprove">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog title="请假申请详情" :visible.sync="viewOpen" width="600px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="申请ID">{{ viewForm.leaveId }}</el-descriptions-item>
        <el-descriptions-item label="用户名称">{{ viewForm.userName }}</el-descriptions-item>
        <el-descriptions-item label="部门名称">{{ viewForm.deptName }}</el-descriptions-item>
        <el-descriptions-item label="请假类型">
          <span v-if="viewForm.leaveType === 'personal'">事假</span>
          <span v-else-if="viewForm.leaveType === 'sick'">病假</span>
          <span v-else-if="viewForm.leaveType === 'annual'">年假</span>
          <span v-else-if="viewForm.leaveType === 'compensatory'">调休</span>
          <span v-else-if="viewForm.leaveType === 'other'">其他</span>
          <span v-else>{{ viewForm.leaveType }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="开始时间">{{ parseTime(viewForm.startTime) }}</el-descriptions-item>
        <el-descriptions-item label="结束时间">{{ parseTime(viewForm.endTime) }}</el-descriptions-item>
        <el-descriptions-item label="请假原因" :span="2">{{ viewForm.reason }}</el-descriptions-item>
        <el-descriptions-item label="申请状态">
          <el-tag :type="getStatusType(viewForm.status)">{{ getStatusText(viewForm.status) }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="申请时间">{{ parseTime(viewForm.createTime) }}</el-descriptions-item>
        <el-descriptions-item label="审批备注" :span="2" v-if="viewForm.status !== '0'">{{ viewForm.remark || '无' }}</el-descriptions-item>
      </el-descriptions>
      <div slot="footer" class="dialog-footer">
        <el-button @click="viewOpen = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listLeave, applyLeave, deleteLeave, approveLeave } from "@/api/system/attendance";
import { parseTime, addDateRange } from "@/utils/ruoyi";

export default {
  name: "AttendanceLeave",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 请假申请表格数据
      leaveList: [],
      // 日期范围
      dateRange: [],
      // 是否显示请假申请弹出层
      leaveOpen: false,
      // 是否显示审批弹出层
      approveOpen: false,
      // 是否显示详情弹出层
      viewOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: null,
        deptName: null,
        leaveType: null,
        status: null
      },
      // 请假申请表单
      leaveForm: {
        leaveType: null,
        startTime: null,
        endTime: null,
        reason: null
      },
      // 请假申请校验
      leaveRules: {
        leaveType: [
          { required: true, message: "请假类型不能为空", trigger: "blur" }
        ],
        startTime: [
          { required: true, message: "开始时间不能为空", trigger: "blur" }
        ],
        endTime: [
          { required: true, message: "结束时间不能为空", trigger: "blur" }
        ],
        reason: [
          { required: true, message: "请假原因不能为空", trigger: "blur" }
        ]
      },
      // 审批表单
      approveForm: {
        leaveId: null,
        status: "1",
        remark: ""
      },
      // 审批校验
      approveRules: {
        status: [
          { required: true, message: "审批结果不能为空", trigger: "blur" }
        ]
      },
      // 详情表单
      viewForm: {}
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询请假申请列表 */
    getList() {
      this.loading = true;
      listLeave(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.leaveList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        leaveId: null,
        userId: null,
        userName: null,
        deptName: null,
        leaveType: null,
        startTime: null,
        endTime: null,
        reason: null,
        status: "0",
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.leaveId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 请假申请按钮操作 */
    handleLeave() {
      this.leaveOpen = true;
      this.leaveForm = {
        leaveType: "personal",
        startTime: null,
        endTime: null,
        reason: null
      };
    },
    // 取消请假申请
    cancelLeave() {
      this.leaveOpen = false;
      this.resetForm("leaveForm");
    },
    // 提交请假申请
    submitLeave() {
      this.$refs["leaveForm"].validate(valid => {
        if (valid) {
          applyLeave(this.leaveForm).then(response => {
            if (response.code === 200) {
              this.$modal.msgSuccess("请假申请提交成功");
              this.leaveOpen = false;
              this.getList();
            } else {
              this.$modal.msgError(response.msg || "请假申请提交失败");
            }
          }).catch(error => {
            console.error("请假申请提交失败:", error);
            this.$modal.msgError("请假申请提交失败，请稍后再试");
          });
        }
      });
    },
    /** 审批按钮操作 */
    handleApprove(row, status) {
      this.approveForm = {
        leaveId: row.leaveId,
        status: status,
        remark: status === "1" ? "审批通过" : "审批驳回"
      };
      if (status) {
        // 如果直接传入状态，则直接提交审批
        this.submitApprove();
      } else {
        // 否则打开审批对话框
        this.approveOpen = true;
      }
    },
    // 取消审批
    cancelApprove() {
      this.approveOpen = false;
      this.resetForm("approveForm");
    },
    // 提交审批
    submitApprove() {
      const { leaveId, status, remark } = this.approveForm;
      const data = { status, remark };
      
      approveLeave(leaveId, data).then(response => {
        if (response.code === 200) {
          this.$modal.msgSuccess("审批成功");
          this.approveOpen = false;
          this.getList();
        } else {
          this.$modal.msgError(response.msg || "审批失败");
        }
      }).catch(error => {
        console.error("审批失败:", error);
        this.$modal.msgError("审批失败，请稍后再试");
      });
    },
    /** 查看详情按钮操作 */
    handleView(row) {
      this.viewForm = { ...row };
      this.viewOpen = true;
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const leaveIds = row.leaveId || this.ids;
      this.$modal.confirm('是否确认删除请假申请编号为"' + leaveIds + '"的数据项?').then(function() {
        return deleteLeave(leaveIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/attendance/leave/export', {
        ...this.queryParams
      }, `leave_${new Date().getTime()}.xlsx`)
    },
    // 状态字典翻译
    getStatusText(status) {
      switch (status) {
        case "0": return "待审批";
        case "1": return "已通过";
        case "2": return "已驳回";
        default: return "未知状态";
      }
    },
    // 状态标签类型
    getStatusType(status) {
      switch (status) {
        case "0": return "warning";
        case "1": return "success";
        case "2": return "danger";
        default: return "info";
      }
    },
    // 添加日期范围
    addDateRange(params, dateRange, propName) {
      return addDateRange(params, dateRange, propName);
    },
    // 格式化时间
    parseTime(time, pattern) {
      return parseTime(time, pattern);
    }
  }
};
</script> 